# -*- coding:utf8 -*-
#
##############################
# Auther : free.won
# Email  : freefis@gmail.com
# Licence on GPL licence
##############################

import os
import sys
import string

from mysite.daohang.models import Site

def sql_format(keyword):
    """
    >>> from mysite.daohang.utils import sql_format as run
    >>> run("bit ftp union")
    >>> '(Q(name__icontains="bit") & Q(name__icontains="ftp") & Q(name__icontains="union")) |
    >>> (Q(pinyin__icontains="bit") & Q(pinyin__icontains="ftp") & Q(pinyin__icontains="union"))'
    SQL: SELECT * FROM mysite_daohang WHERE  .... AND ...  OR ...  like "%....%"
    """
    q_parts = [one for one in keyword.split(' ') if one]
    l = ["Q(name__icontains=\""+one+"\")" for one in q_parts]
    sql1 = reduce(lambda x,y:x+' & '+y,l)
    n = ["Q(pinyin__icontains=\""+one+"\")" for one in q_parts]
    sql2 = reduce(lambda x,y:x+' & '+y,n)
    sql = "(%s) | (%s)"  %(sql1,sql2)
    return  sql


def freshpinyin():
    """ translate the chinese-character into pinyin.\n
        the diff. from zh2py is to force every word to pinyin. and save to DB.
    """
    QuerySet = Site.objects.all()
    for one in QuerySet:
        if not one.pinyin:
            _pinyin = zh2py(one.name)
            if _pinyin:
                one.pinyin = _pinyin
            else:
                one.pinyin = one.name.strip()
            one.save()


def urlcheck_page(request):
    """ check the url to prevent the illegal string. """
    QuerySet = Site.objects.all()
    black_box = {}
    for one in QuerySet:
        one.name=one.name.strip()
        one.save()



def zh2py(input_zh):
    """thanslate chinese-character to pinyin.not save, for being imported """
    def find_it(x, lines):
        ret = []
        for line in lines:
            if line.find(x)!=-1:
                ret.append(line.split(":")[0].strip())
        return ret
    dirname = os.path.dirname(__file__)
    _path = os.path.join(dirname,'pinyin.txt')
    f = open(_path, "r")
    bytes = f.read()
    f.close() 
    lines = bytes.split('\r\n')
    pinyin = ''
    for c in input_zh:
        if c == u'-':
            continue
        if c == " ":
            continue
        if (c in string.letters) or (c in string.digits):
            pinyin += c
            continue
        ret = find_it(c.encode('utf-8'), lines)
        if ret:
            s = ret[0]
            try:
                int(s[-1])
                s = s[:-1]
            except:
                pass
            finally:
                pinyin += s
    return pinyin.strip()
